package com.h3bpm.kumhosunny.crm.controller.dingtalk;

import OThinker.H3.Controller.ControllerBase;
import OThinker.H3.Entity.Settings.CustomSetting;
import com.h3bpm.kumhosunny.common.utils.HttpRequestUtils;
import com.h3bpm.kumhosunny.common.utils.SqlUtil;
import data.DataRow;
import data.DataTable;
import net.sf.json.JSONObject;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;

/**
 * @authormi
 * @date2019/12/4
 */
@Component
public class DingTalkTimer  extends ControllerBase{



    public static void main(String[] args){


        JSONObject  resultJson = HttpRequestUtils.httpGet("https://oapi.dingtalk.com/gettoken?appkey=dingwnfwru7gpm6vda9a&appsecret=XgtC1UtNdg5JVwKPoTEuTe5ekFbrSGTad-Lk5Ns9UI2N5-OjhsEVyKw2GaOD5_IX");

        String token = resultJson.getString("access_token");



    }

    @Scheduled(cron = "0 */30 * * * ?")
    public void updateDingTalkToken() {
    try {
        String getTokenSql = "Select ObjectID,token from k_dingtalk ";
        DataTable dataTable = SqlUtil.doQuery(getTokenSql);
        SimpleDateFormat formatData= new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String dateStr= formatData.format(new Date());
        String ddAppKey = getEngine().getSettingManager().GetCustomSetting(CustomSetting.Setting_DDAppKey);
        String ddAppSecret = getEngine().getSettingManager().GetCustomSetting(CustomSetting.Setting_DDAppSecret);

        JSONObject  resultJson = HttpRequestUtils.httpGet("https://oapi.dingtalk.com/gettoken?appkey="+ddAppKey+"&appsecret="+ddAppSecret);

            if(dataTable!=null && dataTable.getEntityRows()!=null && dataTable.getEntityRows().size()>0){
                DataRow dataRow = dataTable.getEntityRows().get(0);
                String updateToken = "update k_dingtalk set token = '"+resultJson.getString("access_token")+"',ModifiedTime = '"+dateStr+"' where ObjectID = '"+dataRow.getDate("ObjectID")+"'";
                SqlUtil.doNoQuery(updateToken);
            }else{
                String insertToken = "INSERT INTO k_dingtalk (ObjectID,token,CreatedTime,ModifiedTime,otherToken) ";
                String objectId = UUID.randomUUID().toString();
                insertToken=insertToken+"VALUES('"+objectId+"','"+resultJson.getString("access_token")+"','"+dateStr+"','"+dateStr+"','')";
                SqlUtil.doNoQuery(insertToken);
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public String getFunctionCode() {
        return null;
    }
}
